<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title> Chat </title>
    </head>

    <body>
        <div name="contents" id="contents">
            <h1>Chating...</h1>
        </div>
        <form>
            <input type="text" name="say" id="say" value='hello~ ' />
            Your name:<input type="text" name="user" id="user" value='tom' />
            <input type="submit" name="send" id="send" value="send" />
        </form>

        <script src="/socket.io/socket.io.js"></script>
        <script>
            function ID(id){
                return document.getElementById(id);
            }
            function sendToAll(txt){
//                alert(username);
                socket.emit('chat',{msg:txt,from:username,to:'all'});
                var p = document.createElement('p');
                var tx = document.createTextNode('Your say:' + txt);
                p.appendChild(tx);
                contents.appendChild(p);
            }

            var contents = ID('contents');
            var say = ID('say');
            var send = ID('send');
            var user = ID('user');
            var username = '';

            var socket = io.connect('http://localhost:8080');
            socket.on('news',function(data){
                var p = document.createElement('p');
                var tx = document.createTextNode(data.from+' say to '+data.to+':'+data.msg);
                p.appendChild(tx);
                contents.appendChild(p);
            });

            send.onclick = function(){
                username = user.value;
                sendToAll(say.value);
                return false;
            }

        </script>
    </body>
</html>